<?php
/*******************************************************************************
 * 获取主题
 *******************************************************************************/
function get_themes($mark = ''){
	$_themes = array();
	// 读取插件文件
	$themes_dir = @opendir(THR_PTH);
	if($themes_dir){
		while(($dir = readdir($themes_dir)) !== false){
			if(substr($dir, 0, 1) == '.')continue;
			$thr_pth = THR_PTH.$dir.'/';
			if(is_dir($thr_pth)){
				// 尝试默认
				$cfg_file = $thr_pth.'readme.txt';
				$cfg_data = null;
				if(file_exists($cfg_file)){
					$cfg_data = get_config_data($cfg_file);
				}else{

					// 遍历目录
					$theme_subdir = @opendir(THR_PTH.$dir);
					while(($file = readdir($theme_subdir)) !== false){
						if(substr($file, 0, 1) == '.')continue;
						$cfg_file = $thr_pth.$file;
						if(is_dir($cfg_file))continue;
						$ext = substr($file, -4);
						if($ext == '.txt'){
							$cfg_data = get_config_data($cfg_file);
							if($cfg_data){
								break;
							}
						}
					}
					closedir($theme_subdir);
				}

				if(!empty($cfg_data)){
					$cfg_data['mark'] = $dir;
					$_themes[$cfg_data['mark']] = $cfg_data;
				}

			}
		
		// 插件根目录下暂时不允许有插件
		}
		closedir($themes_dir);
	}
	return $_themes;
}

function get_config_data($cfg_file){
	$headers = array(
		'名称'	=> 'name',
		'官网'	=> 'url',
		'版本'	=> 'version',
		'作者'	=> 'author',
		'日期'	=> 'pubdate',
		'说明'	=> 'desc',
		'预览'	=> 'preview',
	);

	$text = file_get_contents($cfg_file);
	$text = preg_replace('/[：:]{3}/', ':::', $text);
	$text = preg_replace('/[;；]{3}/', ';;;', $text);

	$config = array();
	preg_match_all('/([^\s]+)\s*:::\s*([\s\S]+?);;;/', $text, $matchs);
	if(!empty($matchs[1])){
		$arr = array_combine($matchs[1], $matchs[2]);
		foreach($headers as $name => $key){
			if(array_key_exists($name, $arr)){
				if($key == 'preview'){
					$config[$key] = array();
					$preview = explode("\n", trim($arr[$name]));
					foreach($preview as $row){
						$config[$key][] = trim($row);
					}
				}elseif($key == 'desc'){
					$config[$key] = str_replace("\n", '</p><p>', trim($arr[$name]));
					$config[$key] = '<p>'.$config[$key].'</p>';
					$config[$key] = preg_replace('/<p>\s*<\/p>/', '', $config[$key]);
				}else{
					$config[$key] = trim($arr[$name]);
				}
			}
		}
	}
	return $config;
}
/*******************************************************************************
 * 激活主题
 *******************************************************************************/
function activate_theme($mark){
	if(!$theme_all = cache_read('theme_all.php')){
		return false;
	}
	if(array_key_exists($mark, $theme_all)){
		cache_delete('plugin_actions.php');	// 删除动作判断缓存
		$theme = $theme_all[$mark];
		return cache_write('theme.php', $theme);
	}
	return false;
}
?>